package com.iflytek.jcy.supervise.clue.common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

import cn.hutool.core.util.IdUtil;
import com.iflytek.jcy.supervise.clue.common.enums.ResultEnum;
import com.iflytek.jcy.supervise.clue.common.exception.BaseException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2022/4/30
 */
public class FileUtils {

    /**
     * 获取系统临时目录
     *
     * @return
     */
    public static String getTmpDir() throws BaseException {
        String tmpDir = System.getProperty("java.io.tmpdir");
        if (StringUtils.isBlank(tmpDir)) {
            tmpDir = "/tmp";
        }
        File tmpFolder = new File(tmpDir);
        if (!tmpFolder.exists()) {
            try {
                org.apache.commons.io.FileUtils.forceMkdir(tmpFolder);
            }
            catch (IOException e) {
                throw new BaseException(ResultEnum.EXCEPTION, "创建临时目录失败", e);
            }
        }
        return tmpDir;
    }

    public static File writeTmpFile(byte[] fileBytes, String filename) throws IOException {
        String tmpDir = getTmpDir();
        tmpDir = StringUtils.appendIfMissing(tmpDir, File.separator);
        filename = tmpDir + IdUtil.objectId() + filename;
        File file = new File(filename);
        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, fileBytes);
        return file;
    }

    public static boolean deleteQuietly(File videoFile) {
        if (videoFile == null || !videoFile.exists()) {
            return true;
        }

        return org.apache.commons.io.FileUtils.deleteQuietly(videoFile);
    }
    
    /** <br>
	 * 适用场景:获取不带数据的模板 <br>
	 * 调用方式: <br>
	 * 业务逻辑说明<br>
	 *
	 * @param modelName
	 * @return
	 * @throws Exception
	 * @autho dgyu
	 * @time 2022年11月4日 下午5:20:21 */
    public static InputStream getModel(String modelName) throws Exception {
		ClassPathResource defaultFldmlb = new ClassPathResource("directory/" + modelName);
		InputStream in = defaultFldmlb.getInputStream();
		return in;
	}

	/** 复制EXCEL模板，方便后续规则数据写入 <br>
	 * 适用场景: <br>
	 * 调用方式: <br>
	 * 业务逻辑说明<br>
	 *
	 * @param input
	 * @return
	 * @throws Exception
	 * @autho dgyu
	 * @time 2022年11月4日 下午5:19:05 */
	public static File copyModel(InputStream input) throws Exception {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
		Path file = Files.createTempFile(UUID.randomUUID().toString(), ".xlsx");
        org.apache.commons.io.FileUtils.writeByteArrayToFile(file.toFile(), output.toByteArray());
		output.close();
		// 应用退出时删除文件, 兜底
		file.toFile().deleteOnExit();
		return file.toFile();
	}
}
